﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core
{
	public static partial class problem
	{
		public static dynamic getProblemList(int start, int limit, string username, bool god)
		{
			var sql = new Sql.SqlDataContext();
			var total = sql.Problem.Count(row => god || !row.disabled);
			IQueryable result;
			if (!string.IsNullOrEmpty(username)) //User
				result = (from p in sql.Problem
						  from ps in sql.ProblemStatistics
						  where (god || !p.disabled) && ps.pid == p.pid
						  orderby p.pid
						  join so in sql.Solve
						  on new { u = username, p.pid } equals new { u = so.username, so.pid }
						  into sos
						  let so = sos.FirstOrDefault()
						  select new {
							  p.pid,
							  p.title,
							  p.timeLimit,
							  p.memoryLimit,
							  p.description,
							  ps.accept,
							  ps.submit,
							  status = god && p.disabled ? 3 :	//Disabled
								so == null ? 0 :				//Normal
									so.accept > 0 ? 2 :			//Accepted
										so.submit > 0 ? 1 : 0	//Solving
						  }).Skip(start).Take(limit);
			else //Guest
				result = (from p in sql.Problem
						  from s in sql.ProblemStatistics
						  where !p.disabled && s.pid == p.pid
						  orderby p.pid
						  select new {
							  p.pid,
							  p.title,
							  p.timeLimit,
							  p.memoryLimit,
							  p.description,
							  s.accept,
							  s.submit,
							  status = 0
						  }).Skip(start).Take(limit);
			return new {
				success = true,
				total,
				result
			};
		}
	}
}
